/*
 * Copyright (C) 2013 Jeffrey Rusterholz
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package nl.jalava.hitag;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import android.util.Log;

public class TwitterAPI {
	private static final String TWITTER_API = "http://api.twitter.com/1/";
	
	// Public timeline: http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-statuses-public_timeline
	private static final String PUBLIC_TIMELINE = TWITTER_API + "statuses/public_timeline.json";
	
	// User timeline: http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-statuses-user_timeline
	private static final String USER_TIMELINE = TWITTER_API + "statuses/user_timeline.json";
	
	// Search API: http://apiwiki.twitter.com/Twitter-Search-API-Method%3A-search
	private static final String TWITTER_SEARCH = "http://search.twitter.com/search.json?q=";

	// User Show: http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-users%C2%A0show
	private static final String USER_SHOW = "http://api.twitter.com/1/users/show.jsonl?user_id=";
	
	// User search: http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-users-search
	private static final String USER_SEARCH = "http://api.twitter.com/1/users/search.json?q=";
		
	// Trends: http://apiwiki.twitter.com/Twitter-Search-API-Method%3A-trends
	private static final String  TWITTER_TRENDS = "http://search.twitter.com/trends.json";
	
	private static final String USER_AGENT = "hiTag/1.0";
	private static final String SOURCE_PARAMETER = "hiTag";

    private static final Integer DEFAULT_GET_REQUEST_TIMEOUT = 30000;
    private static final Integer DEFAULT_POST_REQUEST_TIMEOUT = 20000;

    private static final String TAG = "hiTag_TwitterAPI";
    
    /**
     * 
     * @return JSONArray
     * @throws Exception
     */
	public JSONArray getPublicTimeLine() throws Exception {
		return new JSONArray(getTwitterRequest(PUBLIC_TIMELINE));		
	}

	/**
	 * 
	 * @param user
	 * @return JSONArray
	 * @throws Exception
	 */
	public JSONArray getUserTimeLine(String user) throws Exception {
		return new JSONArray(getTwitterRequest(USER_TIMELINE + "?screen_name=" + user));		
	}

	/**
	 * 
	 * @param url
	 * @return String
	 * @throws Exception
	 */
	private String getTwitterRequest(String url) throws Exception {
		HttpClient client = new DefaultHttpClient(new BasicHttpParams());
		HttpGet getMethod = new HttpGet(url);
        int statusCode = 0;
		String result = null;

        try {
        	getMethod.setHeader("User-Agent", USER_AGENT);
            client.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, DEFAULT_GET_REQUEST_TIMEOUT);
            client.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, DEFAULT_GET_REQUEST_TIMEOUT);
            HttpResponse httpResponse = client.execute(getMethod);
            statusCode = httpResponse.getStatusLine().getStatusCode();
            result = retrieveInputStream(httpResponse.getEntity());
        } catch (SocketTimeoutException e) {
        	throw e;
        } catch (Exception e) {
        	Log.e(TAG, "postRequest: " + e.toString());
            throw e;
        } finally {
        	getMethod.abort();
        }
		
		return result;		
	}
	
    /**
     * Retrieve the input stream from the HTTP connection.
     * Copyright (C) 2008 Torgny Bjers
     * @param httpEntity
     * @return String
     */
    protected String retrieveInputStream(HttpEntity httpEntity) {
            int length = (int) httpEntity.getContentLength();
            StringBuffer stringBuffer = new StringBuffer(length);
            try {
                    InputStreamReader inputStreamReader = new InputStreamReader(httpEntity.getContent(), HTTP.UTF_8);
                    char buffer[] = new char[length];
                    int count;
                    while ((count = inputStreamReader.read(buffer, 0, length - 1)) > 0) {
                            stringBuffer.append(buffer, 0, count);
                    }
            } catch (UnsupportedEncodingException e) {
                    Log.e(TAG, e.toString());
            } catch (IllegalStateException e) {
                    Log.e(TAG, e.toString());
            } catch (IOException e) {
                    Log.e(TAG, e.toString());
            }
            return stringBuffer.toString();
    }
}
